<template>
  <main>
    <form>
      <div>
        <label class="textLable" for="">文章标题</label>
        <el-input
          style="width: 400px"
          placeholder="请输入文章标题"
          v-model="essayInfo.essayTitle"
        />
      </div>

      <div>
        <label class="textLable" for="file">上传图片</label>
        <el-upload
          id="file"
          action="http://tp.linqiaoyan.top/index.php/admin/Upload/uploadImg"
          list-type="picture-card"
          :auto-upload="true"
          :limit="1"
          :on-success="getFilePath"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions"> </span>
            </div>
          </template>
        </el-upload>
      </div>
      <div>
        <label class="textLable" for="table">文章标签</label>
        <el-checkbox-group id="table" v-model="checkboxGroup2">
          <el-checkbox-button
            v-for="city in cities"
            :key="city"
            :label="city"
            >{{ city }}</el-checkbox-button
          >
        </el-checkbox-group>
      </div>
      <div>
        <label class="textLable" for="">文章摘要</label>
        <el-input
          v-model="essayInfo.summary"
          maxlength="30"
          placeholder="请输入文本摘要"
          show-word-limit
          type="textarea"
        />
      </div>
      <div>
        <label class="textLable" for="editor">文章内容</label>
        <div id="editor" class="editor" ref="editorbox"></div>
      </div>
      <div class="btn">
        <el-button v-if="showBtn" type="primary" @click="addEssayInfo"
          >添加文章</el-button
        >
        <el-button v-else type="primary" @click="updateEssays"
          >修改文章</el-button
        >
      </div>
    </form>
  </main>
  <el-dialog
    v-model="dialogVisible"
    :modal="false"
    :close-on-click-modal="false"
    :show-close="false"
    title="提示"
    width="30%"
    style="z-index: 1000000"
  >
    <span>{{ message }}</span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="toEssayHome">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted } from "vue";
import E from "wangeditor";
import { Plus } from "@element-plus/icons-vue";
import { addEssay, selectIdEssay, updateEssay } from "@/api/serverRequest";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useRouter } from "vue-router";
import axios from "axios";
export default defineComponent({
  name: "",
  props: ["id"],
  components: { Plus },
  setup(props) {
    const checkboxGroup2 = ref(["前端"]);
    const cities = reactive(["前端", "后端", "全栈", "实施", "运维", "测试"]);
    let editorbox = ref();
    let editor = ref();
    let essayInfo = reactive({
      essayTitle: "",
      essayImgPath: "",
      summary: "",
    });
    let dialogVisible = ref(false);
    let router = useRouter();
    let showBtn = ref(true);
    let message = ref("");

    onMounted(() => {
      editor.value = new E(editorbox.value);
      editor.value.config.customUploadImg = async (
        files: (string | Blob)[],
        insert: (arg0: any) => void
      ) => {
        /* files 是 input 中选中的文件列表 */
        let formData = new FormData();
        formData.append("file", files[0]);
        console.log(formData);
        await axios
          .post(
            "http://tp.linqiaoyan.top/index.php/admin/Upload/uploadImg",
            formData,
            {
              headers: { "Content-Type": "multipart/form-data" },
            }
          )
          .then((response) => {
            insert(`http://tp.linqiaoyan.top/${response.data}`);
          });
      };

      editor.value.create();
      if (props.id) {
        showBtn.value = false;
        selectIdEssay(props.id).then((response) => {
          essayInfo.essayTitle = response.data.title;
          essayInfo.essayImgPath = response.data.headImg;
          essayInfo.summary = response.data.summary;
          checkboxGroup2.value.push(...response.data.table.split("|"));
          checkboxGroup2.value.shift();
          editor.value.txt.html(response.data.textInfo);
        });
      }
    });

    function getFilePath(val: string) {
      essayInfo.essayImgPath = val;
    }

    function addEssayInfo() {
      if (
        essayInfo.essayTitle &&
        essayInfo.essayImgPath &&
        checkboxGroup2.value.join("|") &&
        editor.value.txt.html() &&
        essayInfo.summary
      ) {
        addEssay(
          essayInfo.essayTitle,
          essayInfo.essayImgPath,
          checkboxGroup2.value.join("|"),
          editor.value.txt.html(),
          essayInfo.summary
        ).then((response) => {
          if (response?.data.status === 200) {
            message.value = "贡献您!成功添加了数据！";
            dialogVisible.value = true;
          }
        });
      } else {
        ElMessage.error("添加失败，输入的内容不完整，请确保完整性");
      }
    }

    function toEssayHome() {
      dialogVisible.value = false;
      router.push("/home/useressay");
    }

    function updateEssays() {
      updateEssay(
        props.id,
        essayInfo.essayTitle,
        essayInfo.essayImgPath,
        checkboxGroup2.value.join("|"),
        editor.value.txt.html(),
        essayInfo.summary
      ).then((response) => {
        if (response.data.status === 200) {
          message.value = "贡献您!成功修改了数据！";
          dialogVisible.value = true;
        }
      });
    }

    return {
      editorbox,
      checkboxGroup2,
      cities,
      essayInfo,
      getFilePath,
      addEssayInfo,
      dialogVisible,
      toEssayHome,
      showBtn,
      message,
      updateEssays,
    };
  },
});
</script>

<style scoped lang="scss">
main {
  text-align: left;
  width: 80vw;
  margin: 3rem auto;
  .editor {
  }
  .textLable {
    display: block;
    font-weight: bold;
    margin: 10px;
    color: #61649f;
  }

  .btn {
    text-align: right;
    margin-top: 1.5rem;
  }
}
</style>
